package indv.Cshen.cfengsecurityshirodemo.service;

import indv.Cshen.cfengsecurityshirodemo.domain.ShiroUser;
import indv.Cshen.cfengsecurityshirodemo.util.TestData;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Cfeng
 * @date 2022/7/19
 * 简单创建一个模拟的Service供Realm进行验证调用，查询数据库比对
 */

@Component
public class ShiroUserService {
    //根据用户名查找用户，本来要使用dao查询，这里简化
    public ShiroUser queryUserByName(String userName) {
        ShiroUser user = new ShiroUser();
        List<Object> queryUsers = TestData.getAllUsers().stream().filter(us -> userName.equals(us.getUserName())).collect(Collectors.toList());
        if(queryUsers.size() > 0) {
            try {
                //使用的是BeanUtils的克隆
                user = (ShiroUser) BeanUtils.cloneBean(queryUsers.get(0));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }
        return user;
    }

    public ShiroUser queryUserByMobile(String mobile) {
        ShiroUser user = new ShiroUser();
        List<ShiroUser> list = TestData.getAllUsers().stream().filter(us -> Objects.equals(mobile,us.getMobile())).collect(Collectors.toList());
        if(list.size() > 0) {
            try {
                user = (ShiroUser) BeanUtils.cloneBean(list.get(0));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }
        return user;
    }
}
